package com.yzkj.cpjxc.business.service.impl;

import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.IDUtils;
import com.yzkj.cpjxc.business.framework.utils.MD5;
import com.yzkj.cpjxc.business.constants.SecurityMgrConstants;
import com.yzkj.cpjxc.business.domain.SysAuthority;
import com.yzkj.cpjxc.business.service.SysAuthorityService;
import com.yzkj.cpjxc.business.domain.SysDept;
import com.yzkj.cpjxc.business.service.SysDeptService;
import com.yzkj.cpjxc.business.domain.SysRole;
import com.yzkj.cpjxc.business.service.SysRoleService;
import com.yzkj.cpjxc.business.constants.SysUserConstants;
import com.yzkj.cpjxc.business.domain.SysUser;
import com.yzkj.cpjxc.business.domain.SysUserEditPassVo;
import com.yzkj.cpjxc.business.domain.SysUserQueryVo;
import com.yzkj.cpjxc.business.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	public Logger log = Logger.getLogger(SysUserServiceImpl.class);

	/**
	 * MyBatis 命名空间
	 */
	private final static String MAPPER_NAMESPACE = "com.chkj.sysMgr.securityMgr.sysUser.mappers.SysUserMapper";

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	@Autowired
	private SysAuthorityService sysAuthorityService;

	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysDeptService sysDeptService;

	@Override
	public BusinessMap create(SysUserQueryVo sysUser) throws Exception {
		BusinessMap bm = new BusinessMap();
		// 1.1、检查用户是否已经存在
		if (this.isExists(sysUser)) {
			bm.put(Constants.WARNING_MSG, SysUserConstants.USERNAME_EXISTS);
			return bm;
		}
		// 1.2、检查用户的身份证
		if (this.isExistsIdCardNo(sysUser.getIdCardNo())) {
			bm.put(Constants.WARNING_MSG, SysUserConstants.IDCARDNO_EXISTS);
			return bm;
		}
		//2、设置主键
		if (StringUtils.isBlank(sysUser.getUserId())) {
			sysUser.setUserId(IDUtils.genUUID());
		}
		//3、密码采用md5加密
		MD5 md5 = new MD5();
		sysUser.setPassword(md5.encrypt(sysUser.getPassword()));
		//4、设置未删除标记
		sysUser.setDeleteFlag(Constants.DELETE_FLAG_NO);

		//5、保存部门与用户的关系记录。
		String str1 = sysUser.getDeptId();
		if(StringUtils.isBlank(str1)){
			bm.put(Constants.WARNING_MSG, "必须选择一个所属部门");
			return bm;
		}
		String[] sysDepts = str1.split(",");
		for (int i = 0; i < sysDepts.length; i++) {
			//5.1、不为空则新增
			if (!sysDepts[i].toString().isEmpty()) {
				SysUserQueryVo vo = new SysUserQueryVo();
				vo.setDeptId(sysDepts[i].toString());
				vo.setUserId(sysUser.getUserId());
				sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".saveSysDeptUser", vo);
				sqlSessionTemplate.flushStatements();
			}
		}

		// 6、保存用户信息
		sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".add", sysUser);
		return bm;
	}

	@Override
	public boolean isExists(SysUser sysUser) throws Exception {
		//用户名，用户id(可空)，删除状态，判断一个用户是否存在
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isExists", sysUser) > 0;
	}

	@Override
	public SysUser getById(String sysUserId) throws Exception {
		//根据用户id，获取用户详细信息
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getById", sysUserId);
	}

	@Override
	public BusinessMap edit(SysUserQueryVo queryVo) throws Exception {
		BusinessMap bm = new BusinessMap();
		// 1、检查用户是否已经存在
		if (this.isExists(queryVo)) {
			bm.put(Constants.WARNING_MSG, SysUserConstants.USERNAME_EXISTS);
			return bm;
		}
		//2、加密用户密码
		MD5 md5 = new MD5();
		if(StringUtils.isNotBlank(queryVo.getPassword())){
			queryVo.setPassword(md5.encrypt(queryVo.getPassword()));
		}
		
		//3、判断是否有添加部门
		String str1 = queryVo.getDeptId();
		if(StringUtils.isBlank(str1)){
			bm.put(Constants.WARNING_MSG, "必须选择一个所属部门");
			return bm;
		}
		
		//4、不能修改超级管理员用户名
		SysUser su = this.getById(queryVo.getUserId());
		if(su != null){
			if(Constants.ADMIN.equals(su.getUsername()) && !Constants.ADMIN.equals(queryVo.getUsername())){
				bm.put(Constants.WARNING_MSG, "无权限修改超级管理员用户名！");
				return bm;
			}
		}
		
		//5、删除旧的用户与部门关系
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".deleteUserDeptRelation",queryVo.getUserId());

		//6、保存最新部门与用户的关系记录。
		String[] sysDepts = str1.split(",");
		for (int i = 0; i < sysDepts.length; i++) {
			//6.1、不为空则新增
			if (!sysDepts[i].toString().isEmpty()) {
				SysUserQueryVo vo = new SysUserQueryVo();
				vo.setDeptId(sysDepts[i].toString());
				vo.setUserId(queryVo.getUserId());
				sqlSessionTemplate.insert(MAPPER_NAMESPACE + ".saveSysDeptUser", vo);
				sqlSessionTemplate.flushStatements();
			}
		}
		
		//7、最后更新用户信息
		sqlSessionTemplate.update(MAPPER_NAMESPACE + ".edit", queryVo);
		return bm;
	}

	@Override
	public BusinessMap delete(String sysUserId) throws Exception {
		
		BusinessMap bm = new BusinessMap();
		//超级管理员不能删除
		SysUser su = this.getById(sysUserId);
		if(su != null){
			if(Constants.ADMIN.equals(su.getUsername())){
				bm.put(Constants.ERROR_MSG, "无权限删除超级管理员账号！");
				return bm;
			}
		}
		
		//物理删除用户信息
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".delete", sysUserId);
		//物理删除用户与部门关系信息
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".deleteUserDeptRelation", sysUserId);
		//物理删除用户与角色关系信息
		sqlSessionTemplate.delete(MAPPER_NAMESPACE + ".deleteUserRoleRelation", sysUserId);
		return bm;
	}

	@Override
	public Pager<SysUser> search(Pager<SysUser> pager, SysUserQueryVo queryVo) throws Exception {
		//1、查询用户信息
		List<SysUser> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".page", queryVo,
				new RowBounds((pager.getCurrentPage() - 1) * pager.getLimit(), pager.getLimit()));
		pager.setDataList(dataList);
		//2、查询用户信息数量
		Long total = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getTotal", queryVo);
		pager.setTotal(total);
		return pager;
	}

	@Override
	public BusinessMap setRole(SysUserQueryVo queryVo) throws Exception {
		BusinessMap bm = new BusinessMap();
		//先删除数据
		sqlSessionTemplate.delete(SecurityMgrConstants.USER_ROLE_MAPPER_NAMESPACE + ".deleteByUserId", queryVo.getUserId());
		sqlSessionTemplate.flushStatements();

		String[] roleIds = StringUtils.split(queryVo.getRoleIds(), ",");
		Map<String, String> map = null;
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				map = new HashMap<String, String>();
				map.put("userId", queryVo.getUserId());
				map.put("roleId", roleId);
				sqlSessionTemplate.insert(SecurityMgrConstants.USER_ROLE_MAPPER_NAMESPACE + ".add", map);
				sqlSessionTemplate.flushStatements();
			}
		}

		return bm;
	}

	@Override
	public SysUser getSysUserByUsername(String username) throws Exception {
		return sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getSysUserByUsername", username);
	}

	@Override
	public BusinessMap login(SysUser su) throws Exception {
		BusinessMap bm = new BusinessMap();
		SysUser currentUser = this.getSysUserByUsername(su.getUsername());

		// 1、判断用户是否存在，如果不存在则返回
		if (currentUser == null) {
			bm.put(Constants.WARNING_MSG, "用户名或密码错误！");
		} else {// 2、如果存在则判断秘密是否匹配，如果不匹配则返回
			MD5 md5 = new MD5();
			boolean flag = md5.encrypt(su.getPassword()).equals(currentUser.getPassword());
			if (!flag) {
				bm.put(Constants.WARNING_MSG, "用户名或密码错误！");
			} else {
				// 3、判断用户是否激活，如果是停用的则返回
				if (Constants.STATUS_INACTIVE.equals(currentUser.getStatus())) {
					bm.put(Constants.WARNING_MSG, "用户已停用");
				} else {
					// 4、设置用户的角色
					List<SysRole> sysRoles = sysRoleService.getSysRolesByUserId(currentUser.getUserId());
					currentUser.setSysRoles(sysRoles);
					// 5、设置用户的权限集合
					List<SysAuthority> sysAuthoritys = sysAuthorityService.getSysAuthoritysByUserId(currentUser.getUserId());
					currentUser.setSysAuthoritys(sysAuthoritys);
					bm.putToDataMap(Constants.CURRENT_USER, currentUser);
				}
			}
		}
		return bm;
	}

	@Override
	public BusinessMap changePass(SysUserEditPassVo vo) throws Exception {
		BusinessMap bm = new BusinessMap();
		// 1、验证是否为空
		if (StringUtils.isBlank(vo.getPassword())) {
			bm.put(Constants.WARNING_MSG, "请输入原密码");
			return bm;
		}
		if (StringUtils.isBlank(vo.getNewPassword())) {
			bm.put(Constants.WARNING_MSG, "请输入新密码");
			return bm;
		}
		if (StringUtils.isBlank(vo.getConfirmPassword())) {
			bm.put(Constants.WARNING_MSG, "请输入确认新密码");
			return bm;
		}

		MD5 md5 = new MD5();
		// 2、判断原密码是否正确
		if (!vo.getCurrentPassword().equals(md5.encrypt(vo.getPassword()))) {
			bm.put(Constants.WARNING_MSG, "原密码不正确");
		} else {
			// 3、判断新密码和确认密码是否一致
			if (!vo.getNewPassword().equals(vo.getConfirmPassword())) {
				bm.put(Constants.WARNING_MSG, "两次输入密码不一致");
			} else {
				// 4、修改密码
				vo.setNewPassword(md5.encrypt(vo.getNewPassword()));
				sqlSessionTemplate.update(MAPPER_NAMESPACE + ".changePass", vo);
			}
		}
		return bm;
	}

	@Override
	public boolean isExistsIdCardNo(String IdCardNo) throws Exception {
		if (StringUtils.isBlank(IdCardNo)) {
			return false;
		}
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isExistsIdCardNo", IdCardNo) > 0;
	}

	@Override
	public boolean isExistsUserName(String userName) throws Exception {
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isExistsUserName", userName) > 0;
	}

	@Override
	public void initData() throws Exception {
		boolean flag = this.isExistsUserName(Constants.ADMIN);
		if (!flag) {
			// 创建admin用户
			SysUserQueryVo su = new SysUserQueryVo();
			su.setUserId(IDUtils.genUUID());
			su.setPassword(Constants.DEFAULT_PASS);
			su.setUsername(Constants.ADMIN);
			su.setUserCnName(Constants.ADMIN_NAME);
			su.setMobile("18889186045");
			su.setPhone(null);
			su.setEmail(null);
			su.setAddress(null);
			su.setStatus(Constants.STATUS_ACTIVE);
			su.setRemark("这是超级管理员账号");
			su.setDeleteFlag(Constants.DELETE_FLAG_NO);
			su.setIdCardNo(null);
			// 设置admin用户所属部门
			SysDept sd = sysDeptService.getTopLevelDept();//获取顶级部门信息
			if(sd!=null){
				su.setDeptId(sd.getDeptId());
			}
			this.create(su);

			log.info("初始化超级管理员-------------------------------------------------------------------------------------");

			// 设置admin用户的角色（admin）
			SysRole sr = sysRoleService.getRoleByRoleName(Constants.ADMIN);
			SysUserQueryVo queryVo = new SysUserQueryVo();
			queryVo.setUserId(su.getUserId());
			queryVo.setRoleIds(sr.getRoleId());
			this.setRole(queryVo);
			
		}
	}

	@Override
	public boolean isHasUserByDept(String deptId) throws Exception {
		if (StringUtils.isBlank(deptId)) {
			return false;
		}
		return (Integer) sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".isHasUserByDept", deptId) > 0;
	}

	@Override
	public Pager<SysUser> getUserByDeptId(Pager<SysUser> p, SysUserQueryVo queryVo) throws Exception {
		//1、查询用户信息
		List<SysUser> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getUserByDeptIdPage", queryVo,
				new RowBounds((p.getCurrentPage() - 1) * p.getLimit(), p.getLimit()));
		p.setDataList(dataList);
		//2、查询用户信息数量
		Long total = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getUserByDeptIdTotal", queryVo);
		p.setTotal(total);
		return p;
	}
	
	@Override
	public Pager<SysUser> ajaxPageByRoleId(Pager<SysUser> p, SysUserQueryVo queryVo) throws Exception {
		//1、查询用户信息
		List<SysUser> dataList = sqlSessionTemplate.selectList(MAPPER_NAMESPACE + ".getUserByRoleIdPage", queryVo,
				new RowBounds((p.getCurrentPage() - 1) * p.getLimit(), p.getLimit()));
		p.setDataList(dataList);
		//2、查询用户信息数量
		Long total = sqlSessionTemplate.selectOne(MAPPER_NAMESPACE + ".getUserByRoleIdTotal", queryVo);
		p.setTotal(total);
		return p;
	}
}
